<script setup lang="ts">
import {ElMessage, FormInstance} from 'element-plus'
import {reactive, ref} from "vue";
import {adminUserStore} from "@/stores/adminStore";

const adminStore = adminUserStore()
const errorMessage = ref('');
const registerFormRef = ref<FormInstance>();
const registerForm = reactive({
  account: '',
  password: '',
  confirmPassword: '',
});
const rules = {
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== registerForm.password) {
          callback('两次输入的密码不一致!');
        } else {
          callback();
        }
      }, trigger: 'blur'
    },
  ],
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
//重置表单
const resetForm = () => {
  errorMessage.value = '';
  registerForm.account = '';
  registerForm.password = '';
  registerFormRef.value?.resetFields();
}
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 注册接口调用
        await adminStore.register({
          account: registerForm.account,
          password: registerForm.password,
        });
        showMessage('success', "注册成功");
        //toggle.handIsRegister()
        resetForm();
      } catch (error) {
        errorMessage.value = adminStore.errorMessage || '登录失败';
        showMessage('error', "注册失败");
      }
    }
  })
}
</script>

<template>
  <h2>注册</h2>
  <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
  <el-form ref="registerFormRef"
           :model="registerForm"
           :rules="rules"
           size="large"
           scroll-to-error
           hide-required-asterisk>
    <el-form-item prop="account">
      <el-input v-model="registerForm.account" placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" show-password></el-input>
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"
                show-password></el-input>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="submitForm(registerFormRef)" size="large"
             class="register-btn">注册
  </el-button>
</template>

<style scoped>
.register-btn {
  text-align: center;
  font-size: 18px;
  margin-top: 10px;
  width: 50%;
}

.error-message {
  color: red;
}
</style>
